# -*- coding:utf-8 -*-

import os
from pathlib import Path
from typing import Optional

from fastapi import APIRouter, Depends, Request, Query, Body
from sqlalchemy.ext.asyncio import AsyncSession

from config.enums import BusinessType
from config.get_db import get_db
from module_admin.annotation.log_annotation import Log
from module_admin.aspect.interface_auth import CheckUserInterfaceAuth
from module_admin.entity.vo.search_task_vo import (
    SearchTaskModel,
    SearchTaskQueryModel,
    SearchTaskCreateModel,
    SearchTaskUpdateModel,
    OrderRecordQueryModel,
    ManualSearchRequestModel,
    SearchConfigModel
)
from module_admin.entity.vo.user_vo import CurrentUserModel
from module_admin.service.login_service import LoginService
from module_admin.service.search_task_service import (
    SearchTaskService,
    OrderRecordService
)
from utils.log_util import logger
from utils.page_util import PageResponseModel
from utils.response_util import ResponseUtil

searchTaskController = APIRouter(prefix='/agent/task', tags=['搜索任务管理'])


@searchTaskController.get(
    '/list',
    response_model=PageResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:list'))]
)
async def get_task_list(
    request: Request,
    task_query: SearchTaskQueryModel = Depends(SearchTaskQueryModel),
    page_num: int = 1,
    page_size: int = 10,
    filter_user_id: int = Query(None, description="超级管理员切换用户查看（可选，仅管理员可用）"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """获取任务列表（支持用户隔离：非管理员只能看到自己创建的任务）"""
    try:
        # 判断是否是管理员（role_id=1的超级管理员）
        role_id_list = [role.role_id for role in current_user.user.role]
        is_admin = 1 in role_id_list
        
        # ✅ 如果非管理员指定了filter_user_id，忽略（只有管理员可以使用）
        if filter_user_id is not None and not is_admin:
            filter_user_id = None
            logger.warning(f"非管理员用户 {current_user.user.user_id} 尝试使用filter_user_id参数，已忽略")
        
        result = await SearchTaskService.get_task_list(
            db, task_query, page_num, page_size,
            current_user_id=current_user.user.user_id,
            is_admin=is_admin,
            filter_user_id=filter_user_id
        )
        return ResponseUtil.success(model_content=result)
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.get(
    '/logs',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:logs'))]
)
async def get_agent_logs(
    request: Request,
    client_id: str = Query(None, description="客户端ID，可选，如果提供则只查看该客户端的日志"),
    lines: int = Query(500, description="返回最新N行日志，默认500行", ge=1, le=10000)
):
    """
    获取搜索任务实时日志
    读取后端服务自身的日志文件（包含搜索调度器、任务执行等日志）
    支持按客户端ID过滤，返回最新的N行日志
    """
    try:
        # 使用后端服务配置的日志路径（与 log_util.py 中保持一致）
        import time
        logs_dir = Path.cwd() / "logs"
        
        # 如果目录不存在，尝试创建；如果创建失败，检查是否已存在工作目录下的logs
        if not logs_dir.exists():
            try:
                logs_dir.mkdir(parents=True, exist_ok=True)
                logger.info(f"创建日志目录: {logs_dir}")
            except Exception as e:
                logger.warning(f"无法创建日志目录 {logs_dir}: {e}")
                # 如果创建失败但目录已存在，继续使用
                if logs_dir.exists():
                    logger.info(f"日志目录已存在，继续使用: {logs_dir}")
                else:
                    logger.error(f"日志目录不存在且无法创建: {logs_dir}")
                    return ResponseUtil.error(
                        msg=f"日志目录不存在且无法创建: {logs_dir}"
                    )
        
        # 只在首次访问或目录变更时记录日志，避免频繁输出
        # logger.debug(f"使用日志目录: {logs_dir}")
        
        # 获取今日的错误日志文件（格式：YYYY-MM-DD_error.log）
        today = time.strftime("%Y-%m-%d")
        today_log_file = logs_dir / f"{today}_error.log"
        
        # 如果没有今日日志，查找最新的日志文件
        if not today_log_file.exists():
            log_files = sorted(logs_dir.glob("*_error.log"), key=os.path.getmtime, reverse=True)
            if not log_files:
                return ResponseUtil.success(data={"logs": [], "file": None, "total_lines": 0, "message": "暂无日志文件"})
            latest_log_file = log_files[0]
        else:
            latest_log_file = today_log_file
        
        # 读取文件最后N行
        log_lines = []
        try:
            with open(latest_log_file, 'r', encoding='utf-8', errors='ignore') as f:
                # 读取所有行
                all_lines = f.readlines()
                total_lines = len(all_lines)
                
                # 取最后N行
                if client_id:
                    # 如果指定了client_id，过滤包含该ID的行
                    filtered_lines = [line for line in all_lines if client_id in line]
                    log_lines = filtered_lines[-lines:] if len(filtered_lines) > lines else filtered_lines
                else:
                    log_lines = all_lines[-lines:] if total_lines > lines else all_lines
                
        except Exception as e:
            logger.error(f"读取日志文件失败: {e}")
            return ResponseUtil.error(msg=f"读取日志文件失败: {str(e)}")
        
        return ResponseUtil.success(data={
            "logs": log_lines,
            "file": latest_log_file.name,
            "total_lines": len(log_lines),
            "client_id": client_id
        })
        
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.get(
    '/get-current-config',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:manual'))]
)
async def get_current_config(
    request: Request,
    filter_user_id: int = Query(None, description="超级管理员切换用户查看（可选，仅管理员可用）"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    获取当前用户的搜索任务配置（支持管理员查看其他用户）
    用于多设备同步配置
    """
    try:
        # ✅ 判断是否是管理员，如果是管理员且提供了filter_user_id，则查看其他用户的配置
        role_id_list = [role.role_id for role in current_user.user.role]
        is_admin = 1 in role_id_list
        
        target_user_id = current_user.user.user_id
        if is_admin and filter_user_id:
            target_user_id = filter_user_id
            logger.info(f"管理员 {current_user.user.user_id} 查看用户 {filter_user_id} 的配置")
        
        result = await SearchTaskService.get_current_config(
            db=db,
            user_id=target_user_id
        )
        
        if result.get('success'):
            return ResponseUtil.success(
                msg=result.get('msg', '获取配置成功'),
                data=result.get('data')
            )
        else:
            return ResponseUtil.failure(
                msg=result.get('msg', '获取配置失败')
            )
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.get(
    '/get-recent-results',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:manual'))]
)
async def get_recent_results(
    request: Request,
    keyword: Optional[str] = Query(None, description='搜索关键词，不传则返回所有关键词的最新结果'),
    limit: int = Query(30, description='返回数量，默认30'),
    filter_user_id: int = Query(None, description="超级管理员切换用户查看（可选，仅管理员可用）"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    获取最新的搜索结果（从数据库）
    用于页面加载时恢复搜索结果，实现多设备同步
    支持管理员查看其他用户的搜索结果
    """
    try:
        # ✅ 判断是否是管理员（role_id=1的超级管理员）
        role_id_list = [role.role_id for role in current_user.user.role]
        is_admin = 1 in role_id_list
        
        # ✅ 如果非管理员指定了filter_user_id，忽略（只有管理员可以使用）
        if filter_user_id is not None and not is_admin:
            filter_user_id = None
            logger.warning(f"非管理员用户 {current_user.user.user_id} 尝试使用filter_user_id参数，已忽略")
        
        # ✅ 确定目标用户ID
        target_user_id = current_user.user.user_id
        if is_admin and filter_user_id:
            target_user_id = filter_user_id
            logger.info(f"管理员 {current_user.user.user_id} 查看用户 {filter_user_id} 的搜索结果")
        
        result = await SearchTaskService.get_recent_results(
            db=db,
            keyword=keyword,
            limit=limit,
            user_id=target_user_id,
            is_admin=is_admin
        )
        
        if result.get('success'):
            return ResponseUtil.success(
                msg=result.get('msg', '获取搜索结果成功'),
                data=result.get('data')
            )
        else:
            return ResponseUtil.failure(
                msg=result.get('msg', '获取搜索结果失败')
            )
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.get(
    '/users-with-tasks',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:query'))]
)
async def get_users_with_tasks(
    request: Request,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """获取有任务的用户列表（仅管理员可用）"""
    try:
        # 判断是否是管理员
        role_id_list = [role.role_id for role in current_user.user.role]
        is_admin = 1 in role_id_list
        
        if not is_admin:
            return ResponseUtil.error(msg="仅管理员可用")
        
        # 查询所有有任务的用户
        from module_admin.dao.search_task_dao import SearchTaskDao
        from module_admin.entity.do.user_do import SysUser
        from sqlalchemy import select
        
        # 获取所有有任务的用户ID
        tasks = await SearchTaskDao.get_all_tasks_with_users(db)
        user_ids = list(set([int(task.create_by) for task in tasks if task.create_by]))
        
        if not user_ids:
            return ResponseUtil.success(data=[])
        
        # 获取用户信息
        query = select(SysUser).where(
            SysUser.user_id.in_(user_ids),
            SysUser.del_flag == '0'
        )
        result = await db.execute(query)
        users = result.scalars().all()
        
        # 构建返回数据
        user_list = []
        for user in users:
            user_list.append({
                'user_id': user.user_id,
                'user_name': user.user_name,
                'nick_name': user.nick_name or user.user_name
            })
        
        return ResponseUtil.success(data=user_list)
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.get(
    '/{task_id}',
    response_model=SearchTaskModel,
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:query'))]
)
async def get_task_detail(
    request: Request,
    task_id: int,
    db: AsyncSession = Depends(get_db)
):
    """获取任务详情"""
    try:
        task = await SearchTaskService.get_task_detail(db, task_id)
        if task:
            return ResponseUtil.success(model_content=task)
        return ResponseUtil.error(msg='任务不存在')
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.post(
    '/add',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:add'))]
)
@Log(title='搜索任务管理', business_type=BusinessType.INSERT, log_type='operation')
async def add_task(
    request: Request,
    create_data: SearchTaskCreateModel,
    db: AsyncSession = Depends(get_db)
):
    """添加任务"""
    try:
        current_user = request.state.user
        
        task = await SearchTaskService.create_task(
            db, create_data, current_user.user_id, current_user.dept_id
        )
        await db.commit()
        
        return ResponseUtil.success(msg='添加成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.put(
    '/edit',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:edit'))]
)
@Log(title='搜索任务管理', business_type=BusinessType.UPDATE, log_type='operation')
async def edit_task(
    request: Request,
    task_id: int,
    update_data: SearchTaskUpdateModel,
    db: AsyncSession = Depends(get_db)
):
    """编辑任务"""
    try:
        await SearchTaskService.update_task(db, task_id, update_data)
        await db.commit()
        
        return ResponseUtil.success(msg='更新成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.delete(
    '/remove/{task_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:remove'))]
)
@Log(title='搜索任务管理', business_type=BusinessType.DELETE, log_type='operation')
async def remove_task(
    request: Request,
    task_id: int,
    db: AsyncSession = Depends(get_db)
):
    """删除任务"""
    try:
        await SearchTaskService.delete_task(db, task_id)
        await db.commit()
        
        return ResponseUtil.success(msg='删除成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.post(
    '/start/{task_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:start'))]
)
@Log(title='启动搜索任务', business_type=BusinessType.UPDATE, log_type='operation')
async def start_task(
    request: Request,
    task_id: int,
    db: AsyncSession = Depends(get_db)
):
    """启动任务"""
    try:
        await SearchTaskService.start_task(db, task_id)
        await db.commit()
        
        return ResponseUtil.success(msg='任务已启动')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.post(
    '/manual-search',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:manual'))]
)
@Log(title='手动搜索', business_type=BusinessType.OTHER)
async def manual_search(
    request: Request,
    search_config: ManualSearchRequestModel,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    手动搜索
    选择任意一个在线、状态正常的搜索账号执行一次搜索
    """
    try:
        # 将 Pydantic 模型转换为字典
        search_config_dict = search_config.model_dump()
        # ✅ 传递当前用户的user_id，确保搜索结果推送给正确的用户
        result = await SearchTaskService.manual_search(
            db=db,
            search_config=search_config_dict,
            user_id=current_user.user.user_id
        )
        
        if result.get('success'):
            return ResponseUtil.success(
                msg=result.get('msg', '搜索成功'),
                data=result.get('data')
            )
        else:
            return ResponseUtil.failure(
                msg=result.get('msg', '搜索失败')
            )
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@searchTaskController.post(
    '/save-current-config',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:manual'))]
)
@Log(title='保存当前搜索配置', business_type=BusinessType.OTHER)
async def save_current_config(
    request: Request,
    config: SearchConfigModel,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    保存当前用户的搜索任务配置到数据库
    用于多设备同步配置
    """
    try:
        # 将 Pydantic 模型转换为字典
        config_dict = config.model_dump(exclude_none=True)
        result = await SearchTaskService.save_current_config(
            db=db,
            user_id=current_user.user.user_id,
            config=config_dict
        )
        
        if result.get('success'):
            return ResponseUtil.success(
                msg=result.get('msg', '配置已保存'),
                data=result.get('data')
            )
        else:
            return ResponseUtil.failure(
                msg=result.get('msg', '保存配置失败')
            )
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


# @searchTaskController.get(
#     '/get-current-config',
#     dependencies=[Depends(CheckUserInterfaceAuth('agent:task:manual'))]
# )
# async def get_current_config(
#     request: Request,
#     db: AsyncSession = Depends(get_db),
#     current_user: CurrentUserModel = Depends(LoginService.get_current_user)
# ):
#     """
#     获取当前用户的搜索任务配置
#     用于多设备同步配置
#     """
#     try:
#         result = await SearchTaskService.get_current_config(
#             db=db,
#             user_id=current_user.user.user_id
#         )
#
#         if result.get('success'):
#             return ResponseUtil.success(
#                 msg=result.get('msg', '获取配置成功'),
#                 data=result.get('data')
#             )
#         else:
#             return ResponseUtil.failure(
#                 msg=result.get('msg', '获取配置失败')
#             )
#     except Exception as e:
#         logger.exception(e)
#         return ResponseUtil.error(msg=str(e))


# @searchTaskController.get(
#     '/get-recent-results',
#     dependencies=[Depends(CheckUserInterfaceAuth('agent:task:manual'))]
# )
# async def get_recent_results(
#     request: Request,
#     keyword: Optional[str] = Query(None, description='搜索关键词，不传则返回所有关键词的最新结果'),
#     limit: int = Query(30, description='返回数量，默认30'),
#     db: AsyncSession = Depends(get_db),
#     current_user: CurrentUserModel = Depends(LoginService.get_current_user)
# ):
#     """
#     获取最新的搜索结果（从数据库）
#     用于页面加载时恢复搜索结果，实现多设备同步
#     """
#     try:
#         result = await SearchTaskService.get_recent_results(
#             db=db,
#             keyword=keyword,
#             limit=limit
#         )
#
#         if result.get('success'):
#             return ResponseUtil.success(
#                 msg=result.get('msg', '获取搜索结果成功'),
#                 data=result.get('data')
#             )
#         else:
#             return ResponseUtil.failure(
#                 msg=result.get('msg', '获取搜索结果失败')
#             )
#     except Exception as e:
#         logger.exception(e)
#         return ResponseUtil.error(msg=str(e))


@searchTaskController.post(
    '/stop/{task_id}',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:task:stop'))]
)
@Log(title='停止搜索任务', business_type=BusinessType.UPDATE, log_type='operation')
async def stop_task(
    request: Request,
    task_id: int,
    db: AsyncSession = Depends(get_db)
):
    """停止任务"""
    try:
        await SearchTaskService.stop_task(db, task_id)
        await db.commit()
        
        return ResponseUtil.success(msg='任务已停止')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


# 下单记录相关接口
orderRecordController = APIRouter(prefix='/agent/order', tags=['下单记录管理'])


@orderRecordController.get(
    '/list',
    response_model=PageResponseModel,
    dependencies=[Depends(CheckUserInterfaceAuth('agent:order:list'))]
)
async def get_order_list(
    request: Request,
    order_query: OrderRecordQueryModel = Depends(OrderRecordQueryModel),
    page_num: int = 1,
    page_size: int = 10,
    filter_user_id: int = Query(None, description="超级管理员切换用户查看（可选，仅管理员可用）"),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """获取下单记录列表（支持用户隔离：非管理员只能看到自己创建的订单）"""
    try:
        # 判断是否是管理员（role_id=1的超级管理员）
        role_id_list = [role.role_id for role in current_user.user.role]
        is_admin = 1 in role_id_list
        
        # ✅ 如果非管理员指定了filter_user_id，忽略（只有管理员可以使用）
        if filter_user_id is not None and not is_admin:
            filter_user_id = None
            logger.warning(f"非管理员用户 {current_user.user.user_id} 尝试使用filter_user_id参数，已忽略")
        
        result = await OrderRecordService.get_order_list(
            db, order_query, page_num, page_size,
            current_user_id=current_user.user.user_id,
            is_admin=is_admin,
            filter_user_id=filter_user_id
        )
        # ⚠️ 修复：使用 data 参数，确保 rows 和 total 在 data 字段中
        return ResponseUtil.success(data=result)
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@orderRecordController.post(
    '/manual',
    dependencies=[Depends(CheckUserInterfaceAuth('agent:order:manual'))]
)
@Log(title='手动下单', business_type=BusinessType.INSERT)
async def manual_order(
    request: Request,
    item_data: dict = Body(..., description='商品数据'),
    allow_search_accounts: bool = Query(False, description='是否允许使用搜索账号下单（临时方案）'),
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """
    手动下单
    
    Body:
    {
        "item_id": "商品ID",
        "title": "商品标题",
        "price": 价格,
        "keyword": "搜索关键词"
    }
    """
    try:
        result = await OrderRecordService.manual_order(
            db=db,
            item_data=item_data,
            allow_search_accounts=allow_search_accounts,
            create_by=current_user.user.user_id,
            dept_id=current_user.user.dept_id
        )
        
        if result.get('success'):
            return ResponseUtil.success(
                msg=result.get('msg', '下单命令已发送'),
                data=result.get('data')
            )
        else:
            return ResponseUtil.failure(
                msg=result.get('msg', '下单失败')
            )
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@orderRecordController.post(
    '/cancel'
)
async def cancel_order(
    request: Request,
    order_record_id: int = Body(..., description='订单记录ID'),
    reason: str = Body('不想买了', description='取消原因'),
    db: AsyncSession = Depends(get_db)
):
    """取消订单（参考C# MenuCloseSeasonsOrder_Click逻辑）"""
    try:
        logger.info(f"📥 收到取消订单请求: order_record_id={order_record_id}, reason={reason}")
        from module_admin.dao.search_task_dao import OrderRecordDao
        from module_admin.dao.agent_client_dao import AgentClientDao
        from tcp_server.tcp_clients import ClientManager
        import uuid
        
        # ✅ 参考C#代码：1. 获取订单记录
        order_record = await OrderRecordDao.get_record_by_id(db, order_record_id)
        if not order_record:
            return ResponseUtil.error(msg='订单记录不存在')
        
        # ✅ 参考C#代码：2. 获取订单的biz_order_id（对应C#的order.bizOrderId）
        biz_order_id = order_record.biz_order_id
        if not biz_order_id:
            return ResponseUtil.error(msg='订单尚未创建，无法取消')
        
        # ✅ 参考C#代码：3. 根据account_user_id找到对应的Account（对应C#的Account account = DBHelper.Instance.Get<Account>(a => a.UserId == order.AccountUserId)）
        account_user_id = order_record.account_user_id
        if not account_user_id:
            return ResponseUtil.error(msg='无法获取下单账号信息，无法取消订单')
        
        # ✅ 参考C#代码：4. 找到该账户对应的客户端（通过order_record.client_id）
        # 方法：使用订单记录中的client_id，这已经是下单时使用的客户端
        client_info = await AgentClientDao.get_client_by_client_id(db, order_record.client_id)
        if not client_info:
            return ResponseUtil.error(msg='下单账号对应的客户端不存在或已被删除，无法取消订单')
        
        # ✅ 参考C#代码：5. 使用该账户的客户端发送取消订单命令
        logger.info(f"🚀 准备发送取消订单命令: client_id={order_record.client_id}, biz_order_id={biz_order_id}, reason={reason}")
        cmd_message = {
            "event": "cancel_order",
            "direction": "req",
            "success": True,
            "code": 0,
            "msg": "",
            "data": {
                "order_id": biz_order_id,  # ✅ 使用biz_order_id（对应C#的order.bizOrderId）
                "reason": reason  # ✅ 取消原因（对应C#的reason）
            },
            "req_id": str(uuid.uuid4())
        }
        
        # ✅ 重要：使用对应下单的账户（通过order_record.client_id）执行取消
        logger.info(f"📤 发送取消订单命令到客户端: {order_record.client_id}, 命令={cmd_message}")
        ok = await ClientManager.send_to_client(order_record.client_id, cmd_message)
        logger.info(f"📤 取消订单命令发送结果: client_id={order_record.client_id}, success={ok}")
        if ok:
            logger.success(f"✅ 取消订单命令已成功发送: order_id={biz_order_id}, client_id={order_record.client_id}")
            return ResponseUtil.success(msg='取消指令已发送', data={'order_id': biz_order_id})
        logger.error(f"❌ 取消订单命令发送失败: client_id={order_record.client_id}, 客户端可能已离线")
        return ResponseUtil.error(msg='发送失败，客户端可能已离线')
    except Exception as e:
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))


@orderRecordController.delete(
    '/{order_id}'
)
@Log(title='删除订单记录', business_type=BusinessType.DELETE)
async def delete_order(
    request: Request,
    order_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: CurrentUserModel = Depends(LoginService.get_current_user)
):
    """删除订单记录（直接从数据库删除）"""
    try:
        from module_admin.dao.search_task_dao import OrderRecordDao
        
        # ✅ 获取订单记录信息
        order_record = await OrderRecordDao.get_record_by_id(db, order_id)
        if not order_record:
            return ResponseUtil.error(msg='订单记录不存在')
        
        item_id = order_record.item_id
        
        # ✅ 删除订单记录
        await OrderRecordDao.delete_record(db, order_id)
        
        await db.commit()
        
        logger.info(f"订单记录已删除: order_id={order_id}, item_id={item_id}")
        return ResponseUtil.success(msg='删除成功')
    except Exception as e:
        await db.rollback()
        logger.exception(e)
        return ResponseUtil.error(msg=str(e))

